package com.example.administrator.hqq.utils;

import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @name: HQQ
 * @describe:
 * @author: 康海涛 QQ2541849981
 * @time: 2018/12/3 10:57
 * @remark:
 */
public class SketchTextWatcher  implements TextWatcher{
    private int editStart;
    private int editEnd;
    private int maxLen = 12; // 6 个汉字 12 个英文字符 (表情 2 个字符)

    private EditText editText;

    public SketchTextWatcher(EditText e,int maxLen) {
        this.maxLen=maxLen;
        editText = e;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(count - before >= 1){
            CharSequence input = s.subSequence(start + before, start + count);
            if(isEmoji(input.toString())){
                ToastUtils.showShort("不可输入Emoji表情");
                ((SpannableStringBuilder)s).delete(start + before, start + count);
            }
        }

    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.e("kang", "afterTextChanged: "+s.toString() );
        editStart = editText.getSelectionStart();
        editEnd = editText.getSelectionEnd();
        // 先去掉监听器，否则会出现栈溢出
        Log.e("kang", "editStart: "+editStart );
        Log.e("kang", "editEnd: "+editEnd );
        editText.removeTextChangedListener(this);
        if (!TextUtils.isEmpty(s.toString())) {
            while (calculateLength(s.toString()) > maxLen) {
                ToastUtils.showShort("已达到最高输入限制");
                s.delete(--editStart, editEnd--);
                Log.e("kang", "editStart: "+editStart );
                Log.e("kang", "editEnd: "+editEnd);
            }
        }

        editText.setText(s);
        editText.setSelection(editStart);
        // 恢复监听器
        editText.addTextChangedListener(this);
    }

    /**
     * 正则判断emoji表情
     * @param input
     * @return
     */
    private boolean isEmoji(String input){
        Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\ud83e\udc00-\ud83e\udfff]" +
                "|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]");
        Matcher m = p.matcher(input);
        return m.find();
    }

    /**
     * 英文一个字符  中文两个字符
     */
    private int calculateLength(String string) {
        char[] ch = string.toCharArray();
        int varlength = 0;
        for (char c : ch) {
            // changed by zyf 0825 , bug 6918，加入中文标点范围 ， TODO 标点范围有待具体化
            if ((c >= 0x2E80 && c <= 0xFE4F) || (c >= 0xA13F && c <= 0xAA40) || c >= 0x80) { // 中文字符范围0x4e00 0x9fbb
//                    if (c >= 0x4E00 && c <= 0x9FBB) { // 中文字符范围 0x4E00-0x9FA5 + 0x9FA6-0x9FBB
                //中文
                varlength = varlength + 3;
            } else {
                //英文
                varlength=varlength+2;
            }
        }
        return varlength;
    }
    /**
     * 纯英文 纯中文 可以实现 from : http://justwyy.iteye.com/blog/1543419
     * 中英混输入 :
     * 中文 占 2 位
     * 英文 占 1 位
     * 思路：计算 已有文字的长度，计算新增文字的长度，长度没有到达限制时，拼接
     * 小米 输入时，没有边输入边写入EditText的手机有问题，比如小米
     * 华为这种输入一个字符就写入的，没有问题
     */
    private static class SketchLengthFilter implements InputFilter {
        private final int LENGTH_ENGLISH;
        SketchLengthFilter() {
            this(12);
        }
        SketchLengthFilter(int english) {
            LENGTH_ENGLISH = english;
        }
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            int keep = LENGTH_ENGLISH - (calculateLength(dest.toString()) - (dend - dstart));
            end = calculateLength(source.toString());
            CharSequence result = "";
            if(keep >= 0) {
                if (keep >= end - start) {
                    result = null; // keep original
                } else {
                    result = subSequence(source.toString(), start, start + keep);
                }
            }
            return result;
        }

        private CharSequence subSequence(@NonNull String source, int start, int length){
            int size = calculateLength(source);
            if(size < length){
                return source;
            }
            char[] chars = source.toCharArray();
            if(chars.length < length){
                return source;
            }
            char[] result = new char[length - start];
            System.arraycopy(chars, start , result, 0, length);
            return new String(result);
        }
        private int calculateLength(String string){
            int length = 0;
            char[] chars = string.toCharArray();
            for (char c : chars) {
                if (isChinese(c)) {
                    //中文
                    length += 3;
                } else {
                    //英文
                    length+=2;
                }
            }
            return length;
        }
        private boolean isChinese(char c) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
            return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS;
        }
    }
}
